package com.lxiaodd.MallTestApi.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class BaseApiController {

	public String getDataByFile(String fileName) {
		//String filePath =this.getClass().getResource(fileName).getFile();
		String filePath = this.getClass().getClassLoader().getResource(fileName).getPath();//获取文件路径
		String encoding = "UTF-8";  
        File file = new File(filePath);  
        Long filelength = file.length();  
        byte[] filecontent = new byte[filelength.intValue()];  
        try {  
            FileInputStream in = new FileInputStream(file);  
            in.read(filecontent);  
            in.close();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        try {  
            return new String(filecontent, encoding);  
        } catch (UnsupportedEncodingException e) {  
            System.err.println("The OS does not support " + encoding);  
            e.printStackTrace();  
            return null;  
        }  
	}
	
	public List<Map<String,Object>> getListMapByFile(String fileName) throws JsonParseException, JsonMappingException, IOException {
		String data = getDataByFile(fileName);
		ObjectMapper mapper = new ObjectMapper();
		JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, Map.class); 
		List<Map<String,Object>> list =  (List<Map<String,Object>> )mapper.readValue(data, javaType);  
		return list;
	}
	
	public List<Map<String,Object>>  getlistById(String id,List<Map<String,Object>> list,String idName) {		
		List<Map<String,Object>> retlist = new ArrayList<>();
		for(Map<String,Object> map : list) {
			if(map.get(idName).toString().equals(id)) {
				retlist.add(map);
			}
		}
		return retlist;
	}
	
	public Map<String,Object> getMapByFile(String fileName) throws JsonParseException, JsonMappingException, IOException {
		String data = getDataByFile(fileName);
		ObjectMapper mapper = new ObjectMapper();
		Map<String,Object> map = mapper.readValue(data, Map.class);
		return map;
	}
}